<template>
	<view class="cases-page">
		<hs-status-bar></hs-status-bar>
		<top-bar :haveBack="shareId == ''" :haveBackIndex="shareId != ''"></top-bar>
		<hs-phoneModel material-type="example" :materialList="materialList" ref="phoneModel"
			@handleSelectModel="selectModel" @handleSelectMaterial="selectMaterial"></hs-phoneModel>
		<swiper :duration="500" class="list-swiper" vertical next-margin="150rpx" @animationfinish="getList"
			@touchstart="touchstart" @touchend="touchend" @change="swiperChange" :current="current"
			:class="{ animate: shareTips }">
			<swiper-item v-for="(item, index) of list" :key="item.id" :item-id="item.id">
				<view class="list-swiper-item">
					<swiper :duration="500" class="img-swiper" indicator-dots>
						<swiper-item v-for="(i, index) of item.detailList" :key="i.id"
							@click="previewImage(index, item.detailList)">
							<view class="bg" v-if="index == 0"
								:style="{ background: `url(${i.imageUrl})`, backgroundPosition: 'center', backgroundSize: 'cover' }">
							</view>
							<image :src="i.imageUrl" mode="aspectFit" class="img-swiper-item"></image>
						</swiper-item>
					</swiper>
					<button open-type="getPhoneNumber" @getphonenumber.stop="getPhoneNumber($event, item)"
						v-if="!phoneNumber" class="get-phone">授权并获取手机号</button>
					<view class="to-custom" @click=" handleCustom(item)">
						立即定制
					</view>
				</view>
			</swiper-item>
		</swiper>
		<view class="swiper-tips" v-if="shareId && shareTips">
			下划查看更多案例 ↓
		</view>
		<view class="">
			<u-popup :show="showUserQrCode" mode="center" :round="17" @close="handleClose()" closeable
				closeOnClickOverlay>
				<view class="user-qr-code">
					<view class="user-qr-code-title">
						<text>请扫描二维码上传照片</text>
					</view>
					<image class="user-qr-code-image" :src="qrcodeUrl" mode="aspectFit"></image>
					<view class="upload-style" @click="SelectUpload(2)">
						<image src="../../static/images/icon/bd.png" mode="aspectFit"></image>
						拍照上传
					</view>
				</view>
			</u-popup>
			<u-popup :show="showUserImage" :round="17" @close="handleClose()" closeable closeOnClickOverlay
				safeAreaInsetTop activeColor="#333333" class="delivery-steps">
				<view class="upload" v-if="listType == 1">
					<view class="upload-img" v-if="historyImages.length == 0" @click="addUserImage">
						+<br>{{ listType == 1 ? '请上传人像照片' : '请上传图片' }}
					</view>
					<image-swiper :list="historyImages" @change="changeImages" :showDelete="true" v-else
						@delete="deleteUserImage" ref="imageSwiper"></image-swiper>
					<image src="@/static/images/icon/img.png" mode="aspectFit" class="upload-img2" @click="addUserImage"
						v-if="historyImages.length > 0"></image>
					<view class="left" @click="handleSwiperChange('left')">
						<image class="icon" src="@/static/images/icon/vector.png" mode="aspectFit"></image>
					</view>
					<view class="right" @click="handleSwiperChange('right')">
						<image class="icon" src="@/static/images/icon/vector.png" mode="aspectFit"></image>
					</view>
				</view>
				<view class="upload" v-if="listType == 3">
					<view class="tabs">
						<view class="tab" :class="{ active: inputType == 1 }" @click="inputType = 1">
							输入
						</view>
						<view class="tab" :class="{ active: inputType == 2 }" @click="inputType = 2">
							手写
						</view>
					</view>
					<view v-show="inputType == 1">
						<view class="preview" :style="{ fontFamily: activeFontFamily }">
							<view :style="{ color: fontcolor, fontSize: fontsize + 'rpx' }"
								v-for="i of updateText.split('\n').map(line => line.slice(0, 10))" :key="i">
								{{ i.replace(/[\u4e00-\u9fa5]/g, '') }}
							</view>
						</view>
						<view style="display: flex;justify-content: space-around;align-items: center;">
							<!-- <textarea rows="5" v-model="updateText" placeholder="请输入文字" class="textarea"
								always-embed="true"  /> -->
							<textarea rows="5" v-model="updateText" placeholder="请输入字母" class="textarea"
								always-embed="true" @input="handleInput" @compositionstart="compositionStart"
								@compositionend="compositionEnd" />
							<view class="colorbtn" @click="onClick" :style="{ background: fontcolor }"></view>
						</view>


						<scroll-view scroll-y="true" class="scroll">
							<view class="scroll-list">
								<view class="item" @click="activeFontFamily = 'sans-serif'; drawFont()">
									<view>无字体</view>
									<!-- <view class="text">无</view> -->
								</view>
								<view class="item" v-for="item of fontList" :key="item.id"
									@click="activeFontFamily = item.name; drawFont()"
									:style="{ fontFamily: item.name }">
									<!-- {{item.name}} -->
									<image :src="item.icon" mode="aspectFit"
										:style="{ opacity: item.name == activeFontFamily ? 0.3 : 1 }"></image>
									<radio v-if="item.name == activeFontFamily" checked />
									<!-- <view class="text">{{item.name}}</view> -->
								</view>
							</view>

						</scroll-view>
						<chj-color-picker @changecolor="changecolor" ref="chj-color-picker" @change="subColor"
							@cancel="cancel" :defaultColor="fontcolor">
						</chj-color-picker>
					</view>
					<view class="writearea" :class="{ show: inputType != 2 }">
						<canvas type="2d" canvas-id="handwritingCanvas" id="handwritingCanvas" class="write-canvas"
							ref="myCanvas" @touchstart="canvasTouchstart" @touchmove="canvasTouchmove"
							@touchend="canvasTouchend"></canvas>
						<view class="clear" @click="clearCanvas">
							清除
						</view>
					</view>
				</view>
				<view class="upload" v-if="listType == 4">
					<view class="tabs">
						<view class="tab" :class="{ active: inputType == 1 }" @click="inputType = 1">
							输入
						</view>
					</view>
					<view v-show="inputType == 1">
						<!-- <view class="preview" :style="{fontFamily:activeFontFamily}">
							<view :style="{color:fontcolor,fontSize:fontsize +'rpx'}" v-for="i of updateText.split('\n').map(line => line.slice(0, 10))" :key="i">
								{{i.replace(/[\u4e00-\u9fa5]/g, '')}}
							</view>
						</view> -->
						<view class="preview">
							<view>
								<image :src="activeAnimalFontObj.icon" style="width: 180rpx;height: 180rpx;"
									mode="aspectFit"></image>
							</view>
						</view>
						<view style="display: flex;justify-content: space-around;align-items: center;">
							<!-- <textarea rows="5" v-model="updateText" placeholder="请输入文字" class="textarea"
								always-embed="true"  /> -->
							<textarea rows="5" v-model="updateText" placeholder="请输入定制字母（建议6个以内）" class="textarea"
								always-embed="true" @input="handleInput" @compositionstart="compositionStart"
								@compositionend="compositionEnd" />
							<!-- <view class="colorbtn" @click="onClick" :style="{background:fontcolor}"></view> -->
						</view>


						<scroll-view scroll-y="true" class="scroll">
							<view class="scroll-list">
								<!-- <view class="item" @click="activeFontFamily = 'sans-serif';drawFont()">
									<view>无字体</view>
								</view> -->
								<!-- style="height: 200rpx;" -->
								<view class="item" style="height: 160rpx;" v-for="item of fontList" :key="item.id"
									@click="chooseAnimal(item)" :style="{ fontFamily: item.name }">
									<!-- {{item.name}} -->
									<!-- <image :src="item.icon" mode="aspectFit" :style="{opacity:item.name==activeFontFamily?0.3:1}"></image> -->
									<!-- <radio v-if="item.name==activeAnimalFontObj.name " checked/> -->
									<image :src="item.icon" mode="aspectFit"
										:style="{ opacity: (item.id === activeAnimalFontObj.id || item.id === activeCustomItem.fontId) ? 0.3 : 1 }">
									</image>
									<radio
										v-if="item.id === activeAnimalFontObj.id || item.id === activeCustomItem.fontId"
										checked />

									<!-- <view class="text">{{item.name}}</view> -->
								</view>
							</view>

						</scroll-view>
						<!-- <chj-color-picker @changecolor="changecolor" ref="chj-color-picker" @change="subColor"
							@cancel="cancel" :defaultColor="fontcolor">
						</chj-color-picker> -->
					</view>
					<view class="writearea" :class="{ show: inputType != 2 }">
						<canvas type="2d" canvas-id="handwritingCanvas" id="handwritingCanvas" class="write-canvas"
							ref="myCanvas" @touchstart="canvasTouchstart" @touchmove="canvasTouchmove"
							@touchend="canvasTouchend"></canvas>
						<view class="clear" @click="clearCanvas">
							清除
						</view>
					</view>
				</view>
				<view class="upload hs-margin-col-60" v-if="listType == 5">
					<view class="hs-row-between" style="width: 95%;">
						<view class="tabs">
							<view class="tab"
								:style="!checkedAmimalCityContent ? 'background-image: linear-gradient(to right, black 50%, black 50%);background-size: 100% 2px;background-position: center; background-repeat: no-repeat;' : ''"
								:class="{ active: inputType == 1 }" @click="inputType = 1">
								请输入云朵文字（建议40个以内）
							</view>
						</view>
						<u-checkbox-group @change="checkboxGroupChangeContent">
							<u-checkbox v-model="checkedAmimalCityContent" :name="name" label="取消" label-size="12"
								:disabled="!checkedAmimalCityItem"></u-checkbox>
						</u-checkbox-group>
					</view>

					<view style="display: flex;justify-content: space-around;align-items: center;">
						<!-- <textarea rows="5" v-model="updateText" placeholder="请输入文字" class="textarea"
							always-embed="true"  /> -->
						<textarea rows="5" v-model="animalCityFormContent" placeholder="请输入云朵文字" class="textarea"
							always-embed="true" @input="handleInput" @compositionstart="compositionStart"
							@compositionend="compositionEnd" :disabled="!checkedAmimalCityContent" />
						<!-- <view class="colorbtn" @click="onClick" :style="{background:fontcolor}"></view> -->
					</view>
					<view style="margin: 40rpx 0rpx;">
						<view class="hs-row-between" style="width: 95%;">
							<view class="tabs">
								<view class="tab"
									:style="!checkedAmimalCityItem ? 'background-image: linear-gradient(to right, black 50%, black 50%);background-size: 100% 2px;background-position: center; background-repeat: no-repeat;' : ''"
									:class="{ active: inputType == 1 }" @click="inputType = 1">
									请输入云朵物体（建议10个以内）
								</view>
							</view>
							<u-checkbox-group @change="checkboxGroupChangeItem">
								<u-checkbox v-model="checkedAmimalCityItem" :name="name" label="取消" label-size="12"
									:disabled="!checkedAmimalCityContent"></u-checkbox>
							</u-checkbox-group>
						</view>

						<view style="display: flex;justify-content: space-around;align-items: center;">
							<!-- <textarea rows="5" v-model="updateText" placeholder="请输入文字" class="textarea"
								always-embed="true"  /> -->
							<textarea rows="5" v-model="animalCityFormItem" placeholder="请输入云朵物体" class="textarea"
								always-embed="true" @input="handleInput" @compositionstart="compositionStart"
								@compositionend="compositionEnd" :disabled="!checkedAmimalCityItem" />
							<!-- <view class="colorbtn" @click="onClick" :style="{background:fontcolor}"></view> -->
						</view>
					</view>

					<view class="tabs">
						<view class="hs-row-between" style="width: 95%;">
							<view class="tab"
								:style="!checkedAmimalCitySpot ? 'background-image: linear-gradient(to right, black 50%, black 50%);background-size: 100% 2px;background-position: center; background-repeat: no-repeat;' : ''"
								:class="{ active: inputType == 1 }" @click="inputType = 1">
								请输入定制地点（建议10个以内）
							</view>
							<!-- <u-checkbox-group @change="checkboxGroupChangeSpot">
								<u-checkbox 
									v-model="checkedAmimalCitySpot" 
									:name="name"
									label="取消" 
									label-size="12" 
								></u-checkbox>
							</u-checkbox-group> -->
						</view>

					</view>
					<view style="display: flex;justify-content: space-around;align-items: center;">
						<!-- <textarea rows="5" v-model="updateText" placeholder="请输入文字" class="textarea"
							always-embed="true"  /> -->
						<textarea rows="5" v-model="animalCityFormSpot" placeholder="请输入定制地点" class="textarea"
							always-embed="true" @input="handleInput" @compositionstart="compositionStart"
							@compositionend="compositionEnd" :disabled="!checkedAmimalCitySpot" />
						<!-- <view class="colorbtn" @click="onClick" :style="{background:fontcolor}"></view> -->
					</view>
					<view class="writearea" :class="{ show: inputType != 2 }">
						<canvas type="2d" canvas-id="handwritingCanvas" id="handwritingCanvas" class="write-canvas"
							ref="myCanvas" @touchstart="canvasTouchstart" @touchmove="canvasTouchmove"
							@touchend="canvasTouchend"></canvas>
						<view class="clear" @click="clearCanvas">
							清除
						</view>
					</view>
				</view>
				<view class="to-custom" @click="submitUserImage(activeCustomItem)">
					提交
				</view>
			</u-popup>
		</view>

	</view>
</template>

<script>
import {
	getExampleList,
	getStyleList,
	getCustomScrollList,
	getMaterialList,
	getShareInfo,
	getHistoryImages,
	getHistoryBgImages,
	deleteUserImage,
	generateCustomImage,
	generateTextImage,
	getSkuList,
	getFontList,
	UploadQrcode
} from '@/api/custom.js';
import {
	decryptPhoneNumber
} from '@/api/user.js';
import {
	mapGetters,
	mapMutations
} from 'vuex'
import {
	uploadImage,
	uploadTextImage
} from "@/utils/utils.js";
import imageSwiper from '@/pages/example/components/image-swiper/image-swiper.vue'
import eventTracking from "@/utils/eventTracking.js"; //埋点
// if (process.env.NODE_ENV === 'development') {
// 	import 'https://dev-1313492473.cos.ap-guangzhou.myqcloud.com/css/font.css'
// } else {
// 	import 'https://prod-1313492473.cos.ap-guangzhou.myqcloud.com/css/font.css'
// }
export default {
	components: {
		imageSwiper,
	},
	data() {
		return {
			qrcodeUrl: '',
			showUserQrCode: false,
			algorithmName: '',
			checkedAmimalCityContent: true,
			checkedAmimalCityItem: true,
			checkedAmimalCitySpot: true,
			name: '取消',
			animalCityForm: {// 动物城市
				content: '',//云朵文字
				item: '',//物体
				spot: '',//景点
			},
			activeAnimalFontObj: {}, // 选中的动物字体对象
			isComposing: false, // 输入法组合状态
			list: [],
			phoneModelId: 1,
			sort: '',
			activeStyleList: [],
			activeMaterial: '',
			activeMaterialName: '材质',
			activeCustomItem: { fontId: null },
			styleList: [],
			materialList: [],
			current: 0,
			shareId: '',
			shareInfo: {},
			shareTips: false,
			showUserImage: false,
			updateText: '',
			historyImages: [],
			activeUserImageId: '',
			previewEnable: true,
			start: 0,
			client: null,
			listType: null,
			inputType: 1,
			ctx: null,
			lastPoint: null,
			isDrawing: false,
			// 字体
			activeFontFamily: 'sans-serif',
			fontList: [],
			canvas: null,
			showColor: false,
			fontcolor: '#000000',
			CustomDataId: ''
		}
	},
	computed: {
		...mapGetters({ defaultPhoneModelId: 'phoneModelId' }),
		...mapGetters(['getExampleMaterial', 'phoneNumber', 'userInfo']),
		textarr() {
			return this.updateText.split('\n')
		},
		maxtest() {
			let text = ''
			this.updateText.split('\n').forEach(item => {
				text = item.length > text.length ? item : text
			})
			return text
		},
		fontsize() {
			let fontsize = 170 / (this.updateText.length >= 7 ? 2 : 1)
			return fontsize
		},
		animalCityFormContent: {
			get() {
				return this.checkedAmimalCityContent ? this.animalCityForm.content : ''
			},
			set(value) {
				this.animalCityForm.content = value
			}
		},
		animalCityFormItem: {
			get() {
				return this.checkedAmimalCityItem ? this.animalCityForm.item : ''
			},
			set(value) {
				this.animalCityForm.item = value
			}
		},
		animalCityFormSpot: {
			get() {
				return this.checkedAmimalCitySpot ? this.animalCityForm.spot : ''
			},
			set(value) {
				this.animalCityForm.spot = value
			}
		},
	},
	watch: {
		updateText(newValue, oldValue) {
			uni.$u.debounce(() => {
				this.drawFont()
			})

		}
	},
	methods: {
		...mapMutations(['setExampleMaterial', 'setPhoneNumber']),
		checkboxGroupChangeContent(e) {
			// this.checkedAmimalCityContent = e[0] == '取消' ? false : true;
			const newValue = e[0] == '取消' ? false : true;
			// 如果云朵物体已经取消，则不允许取消云朵文字
			if (!newValue && !this.checkedAmimalCityItem) {
				uni.showToast({
					title: '云朵文字和云朵物体不能同时取消',
					icon: 'none',
					duration: 2000
				});
				return;
			}
			this.checkedAmimalCityContent = newValue;
		},
		checkboxGroupChangeItem(e) {
			// this.checkedAmimalCityItem = e[0] == '取消' ? false : true;
			const newValue = e[0] == '取消' ? false : true;
			// 如果云朵文字已经取消，则不允许取消云朵物体
			if (!newValue && !this.checkedAmimalCityContent) {
				uni.showToast({
					title: '云朵文字和云朵物体不能同时取消',
					icon: 'none',
					duration: 2000
				});
				return;
			}
			this.checkedAmimalCityItem = newValue;
		},
		checkboxGroupChangeSpot(e) {
			this.checkedAmimalCitySpot = e[0] == '取消' ? false : true;
		},
		//左右切换图片
		handleSwiperChange(direction) {
			const swiper = this.$refs.imageSwiper
			if (swiper) {
				direction === 'left'
					? swiper.left()
					: swiper.right()
			}
		},
		// 获取手机号授权
		getPhoneNumber(e, item) {
			if (e.detail.code) {
				decryptPhoneNumber({
					code: e.detail.code,
				}).then(response => {
					this.setPhoneNumber(response.data)
					this.handleCustom(item)
				})
			}
		},
		handleInput(e) {
			if (this.isComposing) return; // 输入法组合过程中不处理

			// 使用正则表达式匹配中文字符
			const hasChinese = /[\u4e00-\u9fa5]/.test(this.updateText);

			if (hasChinese) {
				this.showChineseWarning();
			}
		},
		compositionStart() {
			this.isComposing = true;
		},
		compositionEnd() {
			this.isComposing = false;
			this.handleInput(); // 输入法输入完成后再次检查
		},
		showChineseWarning() {
			uni.showToast({
				title: '不能输入中文字符',
				icon: 'none',
				duration: 2000
			});
		},
		// 画字
		onClick() {
			// this.showColor = true
			this.$refs['chj-color-picker'].open();
		},
		subColor({
			hex,
			rgba
		}) {
			// this.showColor = false
			this.fontcolor = hex
			console.log('确定');
			console.log(hex);
			console.log(rgba);
			this.drawFont()

		},
		changecolor(ne) {
			console.log('颜色变化', ne);
			this.fontcolor = ne
			if (this.updateText) {
				this.drawFont()
			}


		},
		cancel() {
			console.log('取消');
			// this.showColor = false

		},
		getList(e) {
			this.previewEnable = true
			this.shareTips = false
			if (e.detail.current == this.list.length - 1 && this.client == 'up') {//手势向上
				this.getCustomScrollList(undefined, this.list[e.detail.current].sort)
			}
			if (e.detail.current == 0 && this.client == 'down') {//手势向下
				this.getCustomScrollList(this.list[e.detail.current].sort)
			}
		},
		// 获取用户历史上传图片
		getHistoryImages() {
			getHistoryImages({
				pageSize: 50
			}).then(res => {
				this.historyImages = res.data
				if (this.historyImages.length > 0) {
					this.activeUserImageId = this.historyImages[0].id
				}
			})

		},
		swiperChange(e) {
			this.current = e.detail.current
			this.previewEnable = false
		},
		// 选择上传方式 
		SelectUpload(value) {
			if (value == 1) {
				UploadQrcode({ stickerId: this.CustomDataId }).then(res => {
					this.qrcodeUrl = res.data
					this.showUserQrCode = true
				})
			} else {
				this.addUserImage()
			}
		},
		// 定制
		handleCustom(data) {
			console.log('handleCustom', data);
			if (this.listType == 1 && this.userInfo.printerId != 0) {
				UploadQrcode({ stickerId: this.CustomDataId }).then(res => {
					this.qrcodeUrl = res.data
					this.showUserQrCode = true
				})
				return
			}
			if (this.listType == 5) {
				this.animalCityForm.content = data.content || ''; // 动物城市
				this.animalCityForm.item = data.item || ''; // 物体
				this.animalCityForm.spot = data.spot || ''; // 景点
				this.showUserImage = true
				this.activeCustomItem = data
				return
			}
			this.getFontList(data)
			if (this.listType == 0) {
				uni.navigateTo({
					url: '/pages/diy/diyPhoneCase'
				})
				return
			}
			this.showUserImage = true
			this.activeCustomItem = data
			// if (this.historyImages.length == 0) {
			// 	this.addUserImage()
			// }
		},
		handleClose() {
			this.showUserImage = false;
			this.showUserQrCode = false;
			this.updateText = '';
			this.clearCanvas();
			if (this.$refs['chj-color-picker']) {
				this.$refs['chj-color-picker'].cancel()
			}
		},
		// 获取当页列表
		async getCustomScrollList(firstSort, lastSort) {
			if (!this.phoneModelId) return
			getCustomScrollList({
				firstSort,
				lastSort,
				sort: firstSort || lastSort ? '' : this.sort,
				materialMap: {
					10: this.activeMaterial,
					11: this.phoneModelId
				},
				type: this.listType,
				algorithmName: this.algorithmName,
				styleIds: this.activeStyleList,
				pageSize: 10,
			}).then(res => {
				let datas = res.data
				if (this.shareId) {
					datas = res.data.filter(item => {
						return item.id != this.shareInfo.id
					})
				}
				if (firstSort) {
					this.list = [...datas, ...this.list]
				} else if (lastSort) {
					this.list = [...this.list, ...datas]
				} else {
					if (this.shareId) {
						this.list = [this.shareInfo, ...datas]
					} else {
						this.list = res.data
					}
				}
				if (datas.length == 0) {
					uni.showToast({
						title: '没有更多了',
						icon: 'none'
					})
				}

			})
		},
		// 放大图片预览
		previewImage(index, list) {
			if (!this.previewEnable) return
			let arr = []
			list.forEach(item => {
				arr.push(item.imageUrl)
			})
			console.log(arr);
			uni.previewImage({
				current: index,
				urls: arr
			});
		},
		// 获取风格列表
		getStyleList() {
			getStyleList({
				type: 2
			}).then(res => {
				this.styleList = res.data
			})
		},
		// 获取机壳列表
		async getMaterialList(phoneModelId) {
			const { data } = await getSkuList({
				materialMap: {
					11: phoneModelId || this.phoneModelId
				},
				pageSize: 50
			})
			// this.$nextTick(() => {
			// 	this.materialList = data.data
			// 	let idx = this.materialList.findIndex(item => {
			// 		return this.activeMaterial == item.materialMap[10]
			// 	})
			// 	idx = idx == -1 ? 0 : idx
			// 	this.selectMaterial(this.materialList[idx], idx)
			// })

			this.materialList = data
			this.animalCityForm.content = data
			const storedMaterial = this.getExampleMaterial
			console.log('storedMaterialCache', storedMaterial);
			let finalIndex = 0
			if (data.length > 0) {

				// 使用可选链和空值合并操作符
				const historyMaterialId = storedMaterial?.materialMap?.[10] ?? null // 先查找历史记录
				// 分步查找策略
				finalIndex = data.findIndex(i =>
					i.materialMap?.[10] === historyMaterialId
				)

				// 未找到历史材质时查找默认项
				if (finalIndex === -1) {
					finalIndex = data.findIndex(item => item.defaulted)
				}

				// 双重保险：当默认项也不存在时取首项
				finalIndex = finalIndex >= 0 ? finalIndex : 0


				finalIndex = Math.max(finalIndex, 0) // 确保下标不小于0
			}
			this.selectMaterial(data[finalIndex], finalIndex)


		},
		// 获取分享的内容
		getShareInfo() {
			getShareInfo({
				shareRecordId: this.shareId
			}).then(res => {
				this.shareInfo = res.data
				this.phoneModelId = this.defaultPhoneModelId
				this.activeMaterial = this.shareInfo.materialId
				this.listType = this.shareInfo.stickerImageType
				uni.$u.debounce(() => {
					this.getCustomScrollList()
				})
				this.shareTips = true
			})
		},
		// 选择手机型号
		selectModel(data) {
			this.$store.commit('setPhoneModelId', data)  // 新增
			this.phoneModelId = data
			if (this.list[this.current]?.sort) {
				this.sort = this.list[this.current].sort
			}
			this.getMaterialList(data)
			// uni.$u.debounce(() => {
			this.getCustomScrollList()
			// })
		},
		// 选择材质
		selectMaterial(data, index) {
			// uni.setStorageSync('defaultMaterial', {
			// 	data,
			// 	index
			// })
			this.setExampleMaterial(data)
			this.$store.commit('setPhoneModelId', this.phoneModelId)  // 新增
			this.activeMaterial = data?.materialMap[10]
			this.$refs.phoneModel.activeMaterialIndex = data.id
			// if (this.materialList.length > 0) {
			// 	this.activeMaterialName = this.materialList[index]?.name
			// }
			if (this.materialList.length > 0) {
				// this.activeMaterialName = this.materialList[index]?.name
				let [{ ...item }] = this.materialList.filter((d) => d.name == data.name)
				console.log('item', item);
				this.activeMaterialName = item.name
				console.log('filter', this.activeMaterialName);
				this.$refs.phoneModel.name = item.name
				this.$refs.phoneModel.baseImageUrl = item.baseImageUrl
				this.$refs.phoneModel.frameImageUrl = item.frameImageUrl
				let extraData = item.materialMap
				eventTracking.event('SWITCH_MATERIAL', 'pages/example', extraData)
			}
			this.$refs.phoneModel.materialListShow = false
			// uni.$u.debounce(() => {
			this.getCustomScrollList()
			// })
		},
		// 选择图片
		addUserImage() {
			let arr
			if (this.userInfo.printerId != 0 && this.userInfo.printerId != null) {
				arr = ['camera']
			} else {
				arr = ['album', 'camera']
			}
			const _this = this
			uni.chooseMedia({
				count: 1, // 最多可以选择的文件个数
				sourceType: arr, // 从相册选择或是直接调起相机
				mediaType: ['image'], // 可以选定的文件类型
				camera: 'back', // 默认后置摄像头，front为前置摄像头
				success: function (res) {
					if (res.tempFiles[0].size > 10 * 1024 * 1024) {
						uni.showToast({
							title: "图片不能大于10M",
							icon: 'none',
							duration: 2000
						})
						return
					}
					uploadImage(res.tempFiles[0].tempFilePath, (resData) => {
						_this.showUserQrCode = false
						uni.showLoading({
							mask: true
						})
						let timer = setTimeout(() => {
							_this.showUserImage = true
							_this.getHistoryImages()
							_this.activeUserImageId = JSON.parse(resData.data).data
							uni.hideLoading()
						}, 2000)
					})
				},
				fail: function (err) {
					console.error('选择失败', err);
				}
			});
		},

		// 滑动选择历史图片
		changeImages(data) {
			this.activeUserImageId = data.id
		},
		// 删除用户上传图片
		deleteUserImage(data, index) {
			const _this = this
			uni.showModal({
				content: '确认要删除',
				success: function (res) {
					if (res.confirm) {
						deleteUserImage({
							id: data.id
						}).then(res => {
							_this.historyImages.splice(index, 1)
							_this.$refs.imageSwiper.setList(index)
						})
					}
				}
			});

		},
		// 选择当前动物风格
		chooseAnimal(item) {
			this.activeAnimalFontObj = {
				id: item.id,
				name: item.name,
				icon: item.icon
			};
			// 同步更新activeCustomItem中的fontId
			this.activeCustomItem.fontId = item.id;
		},
		// 提交定制
		submitUserImage(data) {
			uni.showLoading({
				mask: true
			})
			if (this.listType == 1) {
				if (!this.activeUserImageId) {
					uni.showToast({
						title: "请先选择图片",
						icon: 'none',
						duration: 2000
					})
					uni.hideLoading()
					return
				}
				generateCustomImage({
					userImageId: this.activeUserImageId,
					hasPhoneCase: true,
					stickerId: data.id,
				}).then(res => {
					this.showUserImage = false
					uni.hideLoading()
					uni.showTabBarRedDot({ index: 2 })//不管socket何时相应，点击提交，马上要显示红点（老板要求）
					uni.showToast({
						title: '已提交制作\n稍后可到我的定制页查看',
						icon: 'none'
					});
				})

			} else if (this.listType == 3) {
				if (!this.updateText) {
					uni.showToast({
						title: "请先输入字母",
						icon: 'none',
						duration: 2000
					})
					uni.hideLoading()
					return
				}
				// 新增中文校验
				const hasChinese = /[\u4e00-\u9fa5]/.test(this.updateText);
				if (hasChinese) {
					uni.hideLoading()
					uni.showToast({
						title: '内容包含中文字符，请修改后提交',
						icon: 'none',
						duration: 2000
					})
					return
				}
				// this.clearCanvas()
				uni.canvasToTempFilePath({
					// canvasId: 'handwritingCanvas',
					canvas: this.canvas,
					success: (res) => {
						console.log(res);
						let path = res.tempFilePath
						console.log('aaa', data);
						// return
						console.log('activeFontFamily', this.activeFontFamily);
						uploadTextImage(res.tempFilePath, {
							fontName: this.activeFontFamily,
							hasPhoneCase: 'true',
							stickerId: data.id,
							content: this.updateText,
							flag: this.activeFontFamily == 'sans-serif' ? 'none' : 'image'
						}, (res) => {
							uni.hideLoading()
							const data = JSON.parse(res.data)
							if (data.code == 2001) {
								uni.showToast({
									title: "当前算力不足，请充值",
									icon: 'none',
									duration: 2000
								})
								return
							}
							this.showUserImage = false
							this.updateText = ''
							this.clearCanvas()
							uni.showTabBarRedDot({ index: 2 })//不管socket何时相应，点击提交，马上要显示红点（老板要求）
							uni.showToast({
								title: '已提交制作\n稍后可到我的定制页查看',
								icon: 'none'
							});
						})
					},
					fail: (err) => {
						console.error('导出图片失败', err);
					}
				});
			} else if (this.listType == 4) {
				if (!this.updateText) {
					uni.showToast({
						title: "请先输入字母",
						icon: 'none',
						duration: 2000
					})
					uni.hideLoading()
					return
				}
				// 新增中文校验
				const hasChinese = /[\u4e00-\u9fa5]/.test(this.updateText);
				if (hasChinese) {
					uni.hideLoading()
					uni.showToast({
						title: '内容包含中文字符，请修改后提交',
						icon: 'none',
						duration: 2000
					})
					return
				}
				if (!this.activeAnimalFontObj.hasOwnProperty('icon')) {
					uni.hideLoading()
					uni.showToast({
						title: '请先选择动物字体',
						icon: 'none',
						duration: 2000
					})
					return
				}
				console.log('通过')
				uni.canvasToTempFilePath({
					// canvasId: 'handwritingCanvas',
					canvas: this.canvas,
					success: (res) => {
						console.log(res);
						let path = res.tempFilePath
						let obj = {
							fontName: this.activeAnimalFontObj.name,
							hasPhoneCase: 'true',
							stickerId: data.id,
							content: this.updateText,
							flag: 'none'//动物：none 不需传图
						}
						// return
						uploadTextImage(res.tempFilePath, obj, (res) => {
							uni.hideLoading()
							const data = JSON.parse(res.data)
							if (data.code == 2001) {
								uni.showToast({
									title: "当前算力不足，请充值",
									icon: 'none',
									duration: 2000
								})
								return
							}
							this.showUserImage = false
							this.updateText = ''
							this.clearCanvas()
							uni.showTabBarRedDot({ index: 2 })//不管socket何时相应，点击提交，马上要显示红点（老板要求）
							uni.showToast({
								title: '已提交制作\n稍后可到我的定制页查看',
								icon: 'none'
							});
						})
					},
					fail: (err) => {
						console.error('导出图片失败', err);
					}
				});
			} else if (this.listType == 5) {
				if (this.animalCityForm.spot == '') {
					uni.showToast({
						title: "定制地点不能为空",
						icon: 'none',
						duration: 2000
					})
					uni.hideLoading()
					return
				}
				uni.canvasToTempFilePath({
					// canvasId: 'handwritingCanvas',
					canvas: this.canvas,
					success: (res) => {
						console.log(res);
						let path = res.tempFilePath
						console.log('aaaaaaaaaaaa', data)
						let obj = {
							hasPhoneCase: 'true',
							stickerId: data.id,
							content: this.animalCityForm.content,
							item: this.animalCityForm.item,
							spot: this.animalCityForm.spot,
							flag: 'none'//云朵城市：none 不需传图
						}
						// return
						uploadTextImage(res.tempFilePath, obj, (res) => {
							uni.hideLoading()
							const data = JSON.parse(res.data)
							if (data.code == 2001) {
								uni.showToast({
									title: "当前算力不足，请充值",
									icon: 'none',
									duration: 2000
								})
								return
							}
							this.showUserImage = false
							this.animalCityForm.content = ''; // 清空表单内容
							this.animalCityForm.item = ''; // 清空表单内容
							this.animalCityForm.spot = ''; // 清空表单内容
							this.clearCanvas()
							uni.showTabBarRedDot({ index: 2 })//不管socket何时相应，点击提交，马上要显示红点（老板要求）
							uni.showToast({
								title: '已提交制作\n稍后可到我的定制页查看',
								icon: 'none'
							});
						})
					},
					fail: (err) => {
						console.error('导出图片失败', err);
					}
				});
			}


		},
		touchstart(e) {
			this.start = e.changedTouches[0].clientY
		},
		touchend(e) {
			this.client = (this.start - e.changedTouches[0].clientY) > 0 ? 'up' : 'down'
		},

		// 画板触摸开始
		canvasTouchstart(e) {
			// this.ctx.setStrokeStyle('#000');
			this.ctx.fillStyle = this.fontcolor;
			this.ctx.strokeStyle = this.fontcolor
			// this.ctx.setLineWidth(3);
			const touch = e.touches[0];
			this.lastPoint = {
				x: touch.x,
				y: touch.y
			};
			this.isDrawing = true;
			this.ctx.beginPath()
		},
		// 画板触摸
		canvasTouchmove(e) {
			if (!this.isDrawing) return;
			const touch = e.touches[0];
			const newPoint = {
				x: touch.x,
				y: touch.y
			};
			this.drawLine(this.lastPoint, newPoint);
			// this.ctx.draw(true);
			this.lastPoint = newPoint;
		},
		// 画板触摸结束
		canvasTouchend(e) {
			this.isDrawing = false;
			// this.ctx.draw(true);
		},
		// 绘制线条
		drawLine(from, to) {
			const screenWidth = uni.getWindowInfo().screenWidth
			const pixel = 750 / screenWidth
			this.ctx.moveTo(from.x * pixel, from.y * pixel);
			this.ctx.lineTo(to.x * pixel, to.y * pixel);
			this.ctx.stroke();
		},
		// 清除画板
		clearCanvas() {
			if (!this.ctx) return  // 添加空值校验
			this.ctx.clearRect(0, 0, 750, 750); // 假设 canvas 大小为 300x300，应根据实际情况调整
			// this.ctx.draw();
			this.lastPoint = null;
		},
		// 初始化画板
		initCanvas() {
			wx.createSelectorQuery()
				.select('#handwritingCanvas')
				.node(({
					node: canvas
				}) => {
					this.ctx = canvas.getContext('2d');
					this.canvas = canvas
					canvas.height = 682
					canvas.width = 682
					this.ctx.fillStyle = "#000";
					this.ctx.lineWidth = 6
					this.ctx.lineCap = 'round';
				}).exec();

		},
		// 获取字体列表
		getFontList(data) {
			if (this.listType == 1) return
			let queryData = {
				stickerImageId: data.stickerImageId,
				name: this.listType == 4 ? 'animal' : '',
			}
			getFontList(queryData).then(res => {
				this.fontList = res.data
				// const matchedItem = this.fontList.find(
				// 	item => item.id === this.activeCustomItem.fontId
				// )
				// if(matchedItem) {
				// 	this.activeAnimalFontObj = {
				// 		id: matchedItem.id,
				// 		name: matchedItem.name,
				// 		icon: matchedItem.icon
				// 	}
				// }
				// 新增匹配项置顶逻辑
				const matchedIndex = this.fontList.findIndex(
					item => item.id === this.activeCustomItem.fontId
				);
				if (matchedIndex > -1) {
					// 将匹配项移动到数组首位
					const [matchedItem] = this.fontList.splice(matchedIndex, 1);
					this.fontList.unshift(matchedItem);
					console.log('this.fontList', this.fontList)

					this.activeAnimalFontObj = {
						id: matchedItem.id,
						name: matchedItem.name,
						icon: matchedItem.icon
					}
				}
				// loadFontFace无法缓存字体，比较消耗流量
				this.fontList.forEach(item => {
					item.name = item.name.replace(/ /g, '')
					wx.loadFontFace({
						family: item.name,
						source: item.file,
						scopes: ["native", "webview"],
						success(res) {
							// console.log(item.name, res);
						},
						fail(err) {
							// console.log(item.name, err);
						}
					})
				})
			})
		},
		// 绘制文字canvas
		drawFont() {
			this.clearCanvas()
			let fontSize = 600 / this.textarr.length
			let fontSize1 = 600 / this.maxtest.length
			this.ctx.font = `${Math.floor(fontSize > fontSize1 ? fontSize1 : fontSize)}px ${this.activeFontFamily}`;
			this.ctx.fillStyle = this.fontcolor
			this.ctx.textAlign = 'center';
			for (let i = 0; i < this.textarr.length; i++) {
				this.ctx.fillText(this.textarr[i], 341, Math.floor(fontSize > fontSize1 ? fontSize1 :
					fontSize) * (i + 1));
			}
		},
	},
	// 在返回按钮事件或页面卸载钩子中
	onUnload() {
		const pages = getCurrentPages();
		if (pages.length >= 1) {
			const prevPage = pages[pages.length - 2];
			if (prevPage.route === 'pages/example/example') {
				prevPage.$vm.getRefreshes();
			}
		}
	},
	async onLoad(e) {
		console.log('onLoad', e)
		if (e.scene) {
			uni.setStorageSync('shareRecordId', e.scene)
			this.shareId = e.scene
			await this.getShareInfo()
		} else {
			this.listType = e.type
			this.algorithmName = e.algorithmName
			this.phoneModelId = e.phoneModelId
			this.sort = e.sort || ''// 处理undefined场景
			this.activeMaterial = e.activeMaterial
			this.activeStyleList = e.activeStyleList.split(',').filter(item => {
				return item != ''
			}).map(item => {
				return Number(item)
			})
		}

		await Promise.all([
			this.getStyleList(),
			this.getMaterialList(),
			this.getHistoryImages()
		])
		// 主动加载数据
		this.getCustomScrollList()

		// this.getStyleList()
		// this.getMaterialList()
		// this.getHistoryImages()

		// this.getCustomScrollList()
		// this.getFontList()
	},
	mounted() {

		this.initCanvas();
	},
	onHide() { }
}
</script>

<style lang="scss">
// @import '@/static/style/font-face.scss';

.cases-page {
	display: flex;
	flex-direction: column;
	height: 100%;

	.list-swiper {
		flex-grow: 1;

		.list-swiper-item {
			height: calc(100% - 50rpx);
			background-color: #fff;
			border-radius: 50rpx;
			margin: 20rpx 20rpx;
			box-shadow: 0rpx 1rpx 11rpx 2rpx #ccc;
			overflow: hidden;
			position: relative;

			.img-swiper {
				height: calc(100% - 240rpx);
				// background-color: #eee;
				background-color: #fff;
				transition: height 0.5s;

				.img-swiper-item {
					height: 100%;
					width: 100%;
				}

				.bg {
					// height: 100%;
					// width: 100%;
					// position: absolute;
					// top: 0;
					// left: 0;
					// z-index: -1;
					// filter: blur(12px);
				}
			}

			.to-custom {
				width: 281rpx;
				height: 78.8rpx;
				border-radius: 78rpx;
				font-size: 35rpx;
				box-sizing: border-box;
				text-align: center;
				line-height: 78.8rpx;
				margin: 80rpx auto;
				background-color: #333;
				color: #fff;
			}

			.get-phone {
				height: 78rpx;
				opacity: 0;
				position: absolute;
				bottom: 80rpx;
				left: 50%;
				transform: translate(-50%, 0);
				//width: 250rpx;
			}
		}

		&.animate {
			transition: transform 1s cubic-bezier(.62, -0.14, .62, 1.25);
			animation: down1 1s 2s;
		}

	}

	.swiper-tips {
		position: absolute;
		bottom: 80rpx;
		left: 50%;
		transform: translate(-50%, 0);
		transition: transform 1s cubic-bezier(.62, -0.14, .62, 1.25);
		color: #666;
		animation: down 1s 2s;
	}

	@keyframes down {
		0% {
			transform: translate(-50%, 0);
		}

		50% {
			transform: translate(-50%, -70rpx);
		}

		100% {
			transform: translate(-50%, 0);
		}
	}

	@keyframes down1 {
		0% {
			transform: translate(0, 0);
		}

		50% {
			transform: translate(0, -70rpx);
		}

		100% {
			transform: translate(0, 0);
		}
	}
}

.user-qr-code {
	width: 580rpx;
	height: 580rpx;
	background-color: #fff;
	border-radius: 17rpx;
	display: flex;
	flex-direction: column;
	justify-content: space-around;
	align-items: center;

	.upload-style {
		padding: 20rpx;
		border: 1rpx #e9e9e9 solid;
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 28rpx;

		image {
			width: 66rpx;
			height: 66rpx;
		}
	}

	.user-qr-code-title {
		font-size: 30rpx;
		color: #333;
		text-align: center;
		margin-top: 20rpx;
	}

	.user-qr-code-image {
		width: 80%;
		height: 80%;
		margin: 0 auto;
	}

	.user-qr-code-text {
		font-size: 30rpx;
		color: #333;
		text-align: center;
		margin-top: 20rpx;
	}

}

.upload {
	position: relative;
	overflow: hidden;

	.upload-img {
		height: 350rpx;
		width: 350rpx;
		background-color: #D8D8D8;
		color: #fff;
		text-align: center;
		font-size: 38rpx;
		font-weight: bold;
		padding-top: 115rpx;
		margin: auto;
	}

	.upload-img2 {
		width: 85rpx;
		height: 75rpx;
		position: absolute;
		left: 20rpx;
		bottom: 35rpx;
		overflow: unset;

		&::after {
			content: '添加图片';
			color: #333;
			font-weight: bold;
			white-space: nowrap;
		}
	}

	.left {
		position: absolute;
		height: 42rpx;
		width: 42rpx;
		top: 50%;
		left: 26rpx;
		transform: translateY(-50%) rotate(180deg);

		.icon {
			height: 100%;
			width: 100%;
		}
	}

	.right {
		position: absolute;
		height: 42rpx;
		width: 42rpx;
		top: 50%;
		right: 26rpx;
		transform: translateY(-50%);

		.icon {
			height: 100%;
			width: 100%;
		}
	}

	.tabs {
		display: flex;
		margin: 0 17rpx 17rpx;
		color: #999;

		.tab {
			font-size: 35rpx;
			margin: 0 17rpx;

			&.active {
				font-weight: bold;
				color: #333;
			}
		}
	}

	.label {
		width: 86rpx;
		display: inline-block;
		margin-left: 34rpx;
		font-size: 28rpx;
		line-height: 100rpx;
		vertical-align: top;
	}

	.preview {
		width: calc(100% - 34rpx);
		margin-bottom: 10rpx;
		border-radius: 17rpx;
		padding: 0rpx 30rpx;
		box-sizing: border-box;
		display: inline-block;
		font-size: 170rpx;
		text-align: center;
		overflow: auto;
		white-space: nowrap;
		text-overflow: ellipsis;
		line-height: 1;
		max-height: 350rpx;
		min-height: 173rpx;
	}

	.colorbtn {
		width: 50rpx;
		height: 50rpx;
		margin-right: 34rpx;
	}

	.scroll {
		height: 426rpx;
		margin: 17rpx 34rpx;
		width: calc(100% - 68rpx);
		border: 1rpx solid #ccc;
		// border-radius: 17rpx;

		.scroll-list {
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			grid-gap: 10rpx;
			margin: 10rpx;

			.item {
				border: 1rpx solid #ccc;
				// height: 180rpx;
				height: 100rpx;
				font-size: 38rpx;
				text-align: center;
				line-height: 100rpx;
				position: relative;

				image {
					height: 100%;
					width: 100%;
					// height: 100rpx;
					// margin-top: 17rpx;
					// display: block;
				}

				radio {
					position: absolute;
					top: 0;
					left: calc(50% - 19rpx);
					// top: 50%;
					// left: 50%;
					// transform: translate(-50%, -50%);
				}

				// .text{
				// 	display: block;
				// 	position: absolute;
				// 	width: 100%;
				// 	left: 50%;
				// 	transform: translateX(-50%);
				// 	height: 50rpx;
				// 	line-height: 50rpx;
				// 	font-size: 24rpx;
				// }
			}
		}

	}

	.textarea {
		margin: 0 34rpx;
		border: 1rpx solid #ccc;
		border-radius: 17rpx;
		padding: 16rpx 23rpx;
		width: calc(100% - 68rpx);
		font-size: 33rpx;
		box-sizing: border-box;
		height: 100rpx;
	}

	.writearea {
		margin: 0 34rpx;
		border: 1rpx solid #ccc;
		border-radius: 17rpx;
		width: 682rpx;
		height: 682rpx;

		&.show {
			position: absolute;
			bottom: -1000rpx;
		}

		.write-canvas {
			width: 682rpx;
			height: 682rpx;
		}

		.clear {
			position: absolute;
			bottom: 17rpx;
			right: 51rpx;
			font-size: 34rpx;
			padding: 17rpx;
		}
	}
}

.to-custom {
	width: 281rpx;
	height: 78.8rpx;
	border-radius: 78rpx;
	font-size: 35rpx;
	box-sizing: border-box;
	text-align: center;
	line-height: 78.8rpx;
	margin: 80rpx auto 20rpx;
	background-color: #333;
	color: #fff;
}
</style>